package info.batcloud.fanli.core;

import com.aliyun.opensearch.DocumentClient;
import com.aliyun.opensearch.OpenSearchClient;
import com.aliyun.opensearch.SearcherClient;
import com.aliyun.opensearch.sdk.generated.OpenSearch;
import com.aliyun.oss.OSSClient;
import info.batcloud.fanli.core.aliyun.*;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;

@Configuration
public class AliyunConfig {

    @Bean
    @ConfigurationProperties("aliyun.oss")
    public OSSConfig OSSConfig() {
        return OSSConfig.getInstance();
    }

    @Bean
    @ConfigurationProperties("aliyun.ram")
    public Ram ram() {
        return new Ram();
    }

    @Bean
    @ConfigurationProperties("aliyun.access-key")
    public AccessKey accessKey() {
        return new AccessKey();
    }

    @Bean
    @ConfigurationProperties("aliyun.oss-image")
    public OssImageConfig ossImageConfig() {
        return OssImageConfig.getInstance();
    }


    //ossclient
    @Bean
    @Scope("prototype")
    public OSSClient ossClient() {
        OSSConfig config = OSSConfig();
        AccessKey accessKey = ram().getUsers().getAliyunManager().getAccessKey();
        OSSClient client = new OSSClient(config.getEndpoint(), accessKey.getId(), accessKey.getSecret());
        return client;
    }

    @Bean
    @ConfigurationProperties("aliyun.open-search")
    public OpenSearchConfig openSearchConfig() {
        return new OpenSearchConfig();
    }

    @Bean
    public OpenSearchClient openSearchClient() {
        AccessKey accessKey = ram().getUsers().getAliyunManager().getAccessKey();
        OpenSearchConfig osc = openSearchConfig();
        OpenSearch openSearch = new OpenSearch(accessKey.getId(), accessKey.getSecret(),
                osc.getHostType() == OpenSearchConfig.HostType.internet ? osc.getHost() : osc.getIntranetHost());
        return new OpenSearchClient(openSearch);
    }

    @Bean
    public DocumentClient documentClient() {
        DocumentClient client = new DocumentClient(openSearchClient());
        return client;
    }

    @Bean
    public SearcherClient searcherClient() {
        return new SearcherClient(openSearchClient());
    }

}
